import React, { useState, useRef } from 'react';
import { RouteComponentProps } from 'react-router-dom';
import { Header, Footer, Attestation, Cascader } from '../../components';
import './index.less';
import {
  Collapse,
  Input,
  Button,
  AutoComplete,
  InputNumber,
  Checkbox,
  Radio,
  Select,
  notification,
} from 'antd';
import {
  PlusOutlined,
  CloseCircleOutlined,
  EditOutlined,
} from '@ant-design/icons';
import { optionsClass, optionsAlways } from '../../components/Cascader/option';
import ceshi2 from '../../assets/proimg/ceshi2.jpg';
import { getVINresult } from '../../http/api';
interface inquiryData {
  id: string;
  index: number;
  value: string;
  option:
    | {
        value: string;
        id: string;
      }[]
    | [];
  optionId: string;
  num: number;
  remark: string;
  imgUrl: string[];
  result: {
    partNumber: string;
    standardName: string;
    referencePrice: string;
    accessoryDrawing: string[] | [];
    emptyText: string;
  };
}

interface MatchParams {}
const { Panel } = Collapse;
const { Option } = Select;
export const InquiryIssue: React.FC<RouteComponentProps<MatchParams>> = (
  props
) => {
  // 图片上传ref
  const inputEl = useRef<any>(null);

  // 配件列表默认数据
  const deafultData = [
    {
      id: '111111111111',
      index: 0,
      value: '',
      option: [
        { value: '左大灯', id: '111' },
        { value: 'text 2', id: '222' },
      ],
      optionId: '111',
      num: 2,
      remark: '就是这个件',
      imgUrl: [ceshi2, ceshi2],
      result: {
        partNumber: '33101-SDA-H02',
        standardName: '右前大灯',
        referencePrice: '1028.00',
        accessoryDrawing: [ceshi2, ceshi2],
        emptyText: '请于左侧 手动录入 或 批量粘贴 配件信息！',
      },
    },
    {
      id: '222222222222',
      index: 0,
      value: '',
      option: [],
      optionId: '',
      num: 1,
      remark: '',
      imgUrl: [],
      result: {
        partNumber: '',
        standardName: '',
        referencePrice: '',
        accessoryDrawing: [],
        emptyText: '请于左侧 手动录入 或 批量粘贴 配件信息！',
      },
    },
    {
      id: '33333333',
      index: 0,
      value: '',
      option: [],
      optionId: '',
      num: 1,
      remark: '',
      imgUrl: [],
      result: {
        partNumber: '',
        standardName: '',
        referencePrice: '',
        accessoryDrawing: [],
        emptyText: '请于左侧 手动录入 或 批量粘贴 配件信息！',
      },
    },
    {
      id: '4444444444444',
      index: 0,
      value: '',
      option: [],
      optionId: '',
      num: 1,
      remark: '',
      imgUrl: [],
      result: {
        partNumber: '',
        standardName: '',
        referencePrice: '',
        accessoryDrawing: [],
        emptyText: '请于左侧 手动录入 或 批量粘贴 配件信息！',
      },
    },
  ];

  const [inquiData, setinquiData] = useState<inquiryData[]>(deafultData); // 配件列表数据
  const [VINlist, setVINlist] = useState<any>([]); // VIN下拉列表数据
  const [onfocus, setonfocus] = useState<boolean>(false); // VIN下拉列表是否展开
  const [VINvalue, setVINvalue] = useState<string>(); // VIN输入框内容
  const [VINcheckval, setVINcheckval] = useState<string>(); // VIN选中后内容
  const [imgID, setimgID] = useState<string>(); // 保存图片上传ID
  const Decode = (checkId: string) => {
    const Idarr = checkId.split('-');
    let data = Idarr[0] === '1' ? optionsClass : optionsAlways;
    let resut = {};
    let resdataArr: any[] = [];
    const Dearrayfn = (data: any, Idarr: string[]) => {
      for (let i = 0; i < data.length; i++) {
        if (data[i].value === checkId) {
          resut = data[i];
          return resut;
        } else if (data[i].children.length > 0) {
          Dearrayfn(data[i].children, Idarr);
        }
      }
      return resut;
    };

    const optionsfn = (resdata: any) => {
      if (resdata.children && resdata.children.length > 0) {
        resdata.children.forEach((element: any, i: any) => {
          if (element.children.length > 0) {
            optionsfn(element);
          } else {
            if (resdataArr.indexOf(element.title === -1)) {
              resdataArr.push(element.title);
            }
          }
        });
        return resdataArr;
      } else {
        resdataArr.push(resdata.title);
      }
    };
    return optionsfn(Dearrayfn(data, Idarr));
  };
  console.log(Decode);

  // 输入vin码的确认回调
  const xunjai = () => {
    if (!VINvalue) {
      return;
    }
    let VINlistarr: any[] = [];
    getVINresult({ vin: VINvalue }).then((res: any) => {
      console.log(res);
      if (res.code !== 1) {
        return notification.info({
          message: ``,
          description: res.msg,
        });
      }
      res.data.forEach((element: any) => {
        VINlistarr.push({
          value: (
            <div>
              <span>{element.c_oem_brand}</span>
              <span>{element.c_oem_name_show}</span>
              <span>{element.c_series_BBG}</span>
            </div>
          ),
          id: element.tid,
        });
      });
      setVINlist(VINlistarr);
    });

    setonfocus(!onfocus);
  };

  // 快读询价输入框变化
  const VINsearchOptionchange = (e: any) => {
    setVINvalue(e);
  };

  // 快读询价optiop选中
  const VINchangeOnselect = (value: any, option: any) => {
    console.log(value, option);
    let text = '';
    value.props.children.forEach((element: any) => {
      text += ' ' + element.props.children;
    });
    setVINvalue(VINvalue);
    setonfocus(false);
    setVINcheckval(text.substr(1));
  };

  // 选择品类或常用件后的计算
  const onComputerCheck = (checkData: string[]) => {
    let newinquiData = inquiData.slice();
    checkData.forEach((item, index) => {
      newinquiData.push({
        id: String(newinquiData.length + index),
        index: newinquiData.length + index,
        value: item,
        option: [],
        optionId: '',
        num: 1,
        remark: '',
        imgUrl: [],
        result: {
          partNumber: '',
          standardName: '',
          referencePrice: '',
          accessoryDrawing: [],
          emptyText: '请于左侧 手动录入 或 批量粘贴 配件信息！',
        },
      });
    });
    setinquiData(newinquiData);
  };

  // 选择常用件后的回调
  const onChangealways = (value: string[]) => {
    onComputerCheck(value);
  };

  // 选择品类后的回调
  const onChangeclass = (value: string[]) => {
    onComputerCheck(value);
  };

  // 图片上传 事件绑定
  const ImgUpload = (id: string) => {
    setimgID(id);
    inputEl.current.click();
  };

  // 解析压缩图片
  const ReadImg = (inputFile: any) => {
    const reader = new FileReader();
    reader.readAsDataURL(inputFile);
    reader.onload = function () {
      let img: any = new Image();
      img.src = this.result;
      var width = 750, //图像大小
        height = 1000, //图像大小
        quality = 1, //图像质量
        canvas = document.createElement('canvas'),
        drawer: any = canvas.getContext('2d');
      img.onload = function () {
        const originHeight = img.height;
        const originWidth = img.width;
        let compressedWidth = img.height;
        let compressedHeight = img.width;
        if (originWidth > width && originHeight > height) {
          // 更宽更高，
          if (originHeight / originWidth > height / width) {
            // 更加严重的高窄型，确定最大高，压缩宽度
            compressedHeight = height;
            compressedWidth = height * (originWidth / originHeight);
          } else {
            //更加严重的矮宽型, 确定最大宽，压缩高度
            compressedWidth = width;
            compressedHeight = width * (originHeight / originWidth);
          }
        } else if (originWidth > width && originHeight <= height) {
          // 更宽，但比较矮，以width作为基准
          compressedWidth = width;
          compressedHeight = width * (originHeight / originWidth);
        } else if (originWidth <= width && originHeight > height) {
          // 比较窄，但很高，取maxHight为基准
          compressedHeight = height;
          compressedWidth = height * (originWidth / originHeight);
        } else {
          // 符合宽高限制，不做压缩
        }
        canvas.width = compressedWidth;
        canvas.height = compressedHeight;
        drawer.drawImage(img, 0, 0, canvas.width, canvas.height);

        const imgdata = canvas.toDataURL('image/jpg', quality);
        // console.log(imgdata);
        let newInquiData = inquiData.slice();
        newInquiData.forEach((element) => {
          if (imgID === element.id) {
            element.imgUrl.push(imgdata);
          }
        });
        setinquiData(newInquiData);
      };
    };
  };

  // 图片处理
  const ImghandleChange = (e: any) => {
    for (let i = 0; i < e.target.files.length; i++) {
      ReadImg(e.target.files[i]);
    }
  };

  // 删除图片操作
  const deleteInquieimg = (id: string, imgli: string) => {
    let newInquiData = inquiData.slice();
    newInquiData.forEach((element) => {
      if (id === element.id) {
        element.imgUrl.forEach((item: string, index: number) => {
          if (item === imgli) {
            element.imgUrl.splice(index, 1);
          }
        });
      }
    });
    setinquiData(newInquiData);
  };

  // 配件信息选择
  const changeOnselect = (e: any, id: string) => {
    console.log(e);
    console.log(id);
  };

  // 配件信息输入的监听事件
  const searchOptionchange = (e: any, id: string) => {
    console.log(e);
    let newdeafultData = deafultData;
    newdeafultData[0].option[0].value = e;
    setinquiData(newdeafultData);
  };

  // 删除整行选择的配件信息
  const deleteOption = (id: string) => {
    console.log(id);
    setinquiData(inquiData.filter((item) => item.id !== id));
  };

  // 期望配件品质
  const checkboxOptionpinzhi = [
    { label: '原厂', value: '0' },
    { label: '品牌', value: '1' },
    { label: '原厂再造', value: '2' },
    { label: '拆车件', value: '3' },
    { label: '其他', value: '4' },
  ];

  const checkboxOptioshaop = [
    { label: '平台推荐', value: '5' },
    { label: '自行指定', value: '6' },
  ];

  // 是否需要发票选择
  const isneedInvoice = (key: any) => {
    console.log(key);
  };

  // 顶部车辆信息收起展开回调
  const aaacallback = (key: any) => {
    console.log(key);
  };

  // 发布询价
  const sendInquire = () => {
    let newdeafultData = deafultData;
    newdeafultData[0].option[0].value = '哈哈哈哈哈';
    setinquiData(newdeafultData);
  };

  const tophead = (
    <div className='tophead'>
      <h1>车辆信息</h1>
      <div>
        <span>目前支持品牌：</span>
        <i>
          奔驰、宝马、奥迪、路虎、大众、丰田、本田、日产、奔驰、宝马、奥迪、路虎、保时捷、沃尔沃、捷豹、大众、宾利、玛莎拉蒂、法拉利、宾利、玛莎拉蒂、法拉利、
        </i>
      </div>
      <h2>查看更多</h2>
    </div>
  );
  return (
    <div>
      <Header></Header>
      <Attestation />
      <div className='InquiryIssue'>
        <input
          type='file'
          ref={inputEl}
          hidden
          onChange={ImghandleChange}
          required={true}
          multiple={true}
          accept='image/*'
        />
        <div className='in_top'>
          <Collapse
            defaultActiveKey={['1']}
            onChange={aaacallback}
            expandIconPosition='right'
            ghost={true}
          >
            <Panel header={tophead} key=''>
              <h3>以下是车云链所支持的全车件汽车品牌：</h3>
              <p>
                <span>欧系：</span>
                奔驰、宝马、奥迪、路虎、保时捷、沃尔沃、捷豹、大众、宾利、玛莎拉蒂、法拉利、兰博基尼、劳斯莱斯、斯柯达、标致、雪铁龙、雷诺
              </p>
              <p>
                <span>美系：</span>
                凯迪拉克、福特、别克、雪佛兰、吉普、克莱斯勒、林肯、道奇
              </p>
              <p>
                <span>日系：</span>
                雷克萨斯、丰田、本田、日产、马自达、斯巴鲁、三菱、英菲尼迪、讴歌
              </p>
              <p>
                <span> 韩系：</span> 现代、起亚 国产：猎豹
              </p>
            </Panel>
          </Collapse>

          <div className='xunjia'>
            <span>VIN 码询价</span>
            <AutoComplete
              value={VINvalue}
              className='searchvin'
              placeholder='原厂零件号或配件名称'
              options={VINlist}
              onChange={(event) => VINsearchOptionchange(event)}
              onSelect={(value, option) => VINchangeOnselect(value, option)}
              autoFocus={onfocus}
              open={onfocus}
              defaultActiveFirstOption={true}
              dropdownMatchSelectWidth={false}
            />
            <Button type='primary' onClick={xunjai}>
              快速询价
            </Button>
          </div>

          {VINcheckval ? (
            <div className='beihuo'>
              <span>{VINcheckval}</span>
            </div>
          ) : null}
          <div className='beihuo'>
            无VIN码，您可以 <a href='/'>备货询价</a>
          </div>
        </div>

        <div className='peijian'>
          <div className='title peijaintitle'>
            <div className='mdiv'>
              <h1>录入配件信息</h1>

              <Cascader
                data={optionsAlways}
                placeholder='按常用件选择'
                onChange={(res) => onChangealways(res)}
              ></Cascader>
              <Cascader
                data={optionsClass}
                placeholder='按品类选择'
                onChange={(res) => onChangeclass(res)}
              ></Cascader>
            </div>
            <div className='mdiv'>
              <span>您还可以</span>
              <a href='/'>自助查找配件</a>
            </div>
          </div>

          <div className='pei_list'>
            <ul className='pl_title pl_list'>
              <li>序号</li>
              <li>配件信息</li>
              <li>数量</li>
              <li>备注</li>
              <li>配件实物图片</li>
              <li>
                <span>原厂零件号</span>
                <span>标准名称</span>
                <span>4S店参考价(¥)</span>
                <span>配件图</span>
                <span></span>
              </li>
            </ul>
            {inquiData.map((item, i) => (
              <ul className='pl_body pl_list' key={item.id}>
                <li>{i + 1}</li>
                <li>
                  <Input.Group compact>
                    <AutoComplete
                      style={{ width: '90%' }}
                      placeholder='原厂零件号或配件名称'
                      options={item.option}
                      value={item.value}
                      onChange={(event) => searchOptionchange(event, item.id)}
                      onSelect={(event) => changeOnselect(event, '12313')}
                    />
                  </Input.Group>
                </li>
                <li>
                  <InputNumber
                    min={1}
                    style={{ width: '90%' }}
                    defaultValue={item.num}
                  />
                </li>
                <li>
                  <Input
                    style={{ width: '90%' }}
                    placeholder=''
                    defaultValue={item.remark}
                  />
                </li>
                <li>
                  <dl className='imgcheck'>
                    {item.imgUrl.length < 3 ? (
                      <dt onClick={() => ImgUpload(item.id)}>
                        <PlusOutlined />
                      </dt>
                    ) : null}
                    {item.imgUrl.map((imgli: string, key: number) => (
                      <dd key={key}>
                        <CloseCircleOutlined
                          onClick={() => deleteInquieimg(item.id, imgli)}
                        />
                        <h1>
                          <img className='biimg' src={imgli} alt='' />
                        </h1>
                      </dd>
                    ))}
                  </dl>
                </li>
                {item.result.partNumber !== '' ? (
                  <li>
                    <span>{item.result.partNumber}</span>
                    <span>{item.result.standardName}</span>
                    <span>{item.result.referencePrice}</span>
                    <span>
                      {item.result.accessoryDrawing.map(
                        (drawimg: string, draykey: number) => (
                          <h1 key={draykey}>
                            <img className='biimg' src={drawimg} alt='' />
                          </h1>
                        )
                      )}
                    </span>
                    <span onClick={() => deleteOption(item.id)}>
                      <CloseCircleOutlined />
                    </span>
                  </li>
                ) : (
                  <li>
                    <i>
                      请于左侧 手动录入 或 批量粘贴 配件信息！
                      <a href='/'>查看操作指南</a>
                    </i>
                    <i onClick={() => deleteOption(item.id)}>
                      <CloseCircleOutlined />
                    </i>
                  </li>
                )}
              </ul>
            ))}
          </div>
        </div>

        <div className='checklist'>
          <div className='title'>
            <h1>录入配件信息</h1>
          </div>
          <div>
            <div className='checkboxli'>
              <i>是否需要发票：</i>
              <Radio.Group onChange={isneedInvoice}>
                <Radio value={1}>不需要发票</Radio>
                <Radio value={2}>需要发票</Radio>
              </Radio.Group>
            </div>
            <div className='checkboxli'>
              <i>期望配件品质：</i>
              <Checkbox.Group
                options={checkboxOptionpinzhi}
                defaultValue={['']}
                onChange={isneedInvoice}
              />
            </div>
            <div className='checkboxli'>
              <i>期望的商家：</i>
              <Checkbox.Group
                options={checkboxOptioshaop}
                defaultValue={['']}
                onChange={isneedInvoice}
              />
            </div>
          </div>
        </div>

        <div className='contentbox'>
          <div className='title'>
            <h1>联系方式</h1>
            <span>
              <EditOutlined />i <a href='/'>管理收获地址</a>
            </span>
          </div>
          <div className='checkbox'>
            <i>收货地址：</i>
            <Select
              defaultValue='lucy'
              style={{ width: 478, height: 36 }}
              onChange={isneedInvoice}
            >
              <Option value='jack'>
                dabai 183 9485 9686 北京市 北京城区 朝阳区 平房镇
                北京市朝阳区平房乡石各庄村东
              </Option>
              <Option value='lucy'>Lucy</Option>
              <Option value='disabled' disabled>
                Disabled
              </Option>
              <Option value='Yiminghe'>yiminghe</Option>
            </Select>
          </div>
        </div>

        <div className='buttonbtm'>
          <Button
            type='primary'
            shape='round'
            size='large'
            block
            onClick={sendInquire}
          >
            发布询价
          </Button>
        </div>
      </div>
      <Footer></Footer>
    </div>
  );
};
